package cn.lonecloud.randomCall.help;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import cn.lonecloud.randomCall.model.Student;
import cn.lonecloud.util.ExcelUtil;

/**
 * 随机点名的帮助层
 * 
 * @Title: RandomCallHelp.java
 * @Package cn.lonecloud.randomCall
 * @Description:
 * @author lonecloud
 * @date 2016年10月28日 下午1:00:39
 */
public class RandomCallHelp {

	// 文件
	private File file;
	// 数据集
	List<Row> list;
	// util
	ExcelUtil excelUtil;

	List<Integer> countList = new ArrayList<>();

	public RandomCallHelp(File file) throws IOException {
		super();
		this.file = file;
		excelUtil = new ExcelUtil(file.getAbsolutePath());
		list = excelUtil.readExcel(file.getAbsolutePath());
		excelUtil.setOverWrite(false);
		countList.add(0);
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public Student RandomExcel() {
		Student student = new Student();
		int nextInt = 0;
		if (list != null && list.size() != 0) {
			if (countList.size()==list.size()) {
				student.setStudentName("点名完成");
				return student;
			}
			do {
				double random = Math.random() * list.size();
				nextInt = (int) random;
			} while (countList.contains(nextInt));
			Row row = list.get(nextInt);
			Cell numCell = row.getCell(0);// 学号
			Cell nameCell = row.getCell(1);// 名字
			student.setId(nextInt);
			student.setStudentNum(numCell.getStringCellValue());
			student.setStudentName(nameCell.getStringCellValue());
			countList.add(nextInt);
			return student;
		}
		return null;
	}

	/**
	 * 将数据写入文件
	 * 
	 * @Description:
	 * @param student
	 * @throws IOException
	 */
	public void setstatus(Student student) throws IOException {
		Row row = list.get(student.getId());
		Cell statusCell = row.createCell(2);
		int status = student.getStatus();
		System.out.println(student);
		if (status == 0) {
			statusCell.setCellValue("*");
		}
		if (status == 1) {
			statusCell.setCellValue("x");
		}
		if (status == 2) {
			statusCell.setCellValue("请假");
		}
	}

	/**
	 * 保存
	 * 
	 * @Description:
	 * @throws IOException
	 */
	public void save() throws IOException {
		excelUtil.writeExcel(list, file.getAbsolutePath());
	}
}
